#ifndef MESSAGE_H
#define MESSAGE_H

#include <vector>
#include <cstdint>
#include <string>
#include <arpa/inet.h>
#include "json.hpp"

using json = nlohmann::json;

#define MAGIC_NUMBER 0xA13B

#pragma pack(push, 1)

// 消息类型扩展
enum class MessageType : uint8_t
{
    INVALID = 0x00,
    LOGIN_REQ = 0x01,
    LOGIN_RESP = 0x02,
    GROUP_MSG_SEND = 0x03,
    GROUP_MSG_ACK = 0x04,
    ACK = 0x11,
    HEARTBEAT = 0x05,
    REGISTER_REQ = 0x06,
    REGISTER_RESP = 0x07
};

// 内容类型扩展
enum class ContentType : uint8_t
{
    UNKNOWN = 0x00,
    JSON = 0x01,
    TEXT = 0x02,
    BINARY = 0x03
};

// 协议头（16字节严格对齐）
struct MessageHeader
{
    uint16_t magic;           // 魔数
    uint16_t version;         // 主版本<<8 | 次版本
    uint32_t seq_num;         // 消息序号（网络字节序）
    MessageType msg_type;     // 消息类型
    ContentType content_type; // 内容格式
    uint16_t body_len;        // Body部分长度（不含头）
    uint32_t checksum;        // CRC32校验码（计算时置0）

    void hton() noexcept
    {
        magic = htons(magic);
        version = htons(version);
        seq_num = htonl(seq_num);
        body_len = htons(body_len);
        checksum = htonl(checksum);
    }

    void ntoh() noexcept
    {
        magic = ntohs(magic);
        version = ntohs(version);
        seq_num = ntohl(seq_num);
        body_len = ntohs(body_len);
        checksum = ntohl(checksum);
    }
};
static_assert(sizeof(MessageHeader) == 16, "Header大小错误");

//注册请求 (REGISTER_REQ)
struct RegisterRequest {
    std::string username;
    std::string password;

    static json to_json(const RegisterRequest& req) {
        return {
            {"username", req.username},
            {"password", req.password}
        };
    }

    static RegisterRequest from_json(const json& j) {
        return {
            j.at("username").get<std::string>(),
            j.at("password").get<std::string>()
        };
    }
};

// 注册响应 (REGISTER_RESP)
struct RegisterResponse {
    int32_t result;     // 0-成功，其他-错误码
    std::string error_msg;

    static json to_json(const RegisterResponse& resp) {
        return {
            {"result", resp.result},
            {"error_msg", resp.error_msg}
        };
    }

    static RegisterResponse from_json(const json& j) {
        return {
            j.at("result").get<int32_t>(),
            j.value("error_msg", "")
        };
    }
};
// 登录请求 (LOGIN_REQ)
struct LoginRequest {
    std::string username;
    std::string password;

    static json to_json(const LoginRequest& req) {
        return {
            {"username", req.username},
            {"password", req.password}
        };
    }

    static LoginRequest from_json(const json& j) {
        return {
            j.at("username").get<std::string>(),
            j.at("password").get<std::string>()
        };
    }
};
// 登录响应 (LOGIN_RESP)
struct LoginResponse {
    int32_t result;     // 0-成功，其他-错误码
    std::string error_msg;

    static json to_json(const LoginResponse& resp) {
        return {
            {"result", resp.result},
            {"error_msg", resp.error_msg}
        };
    }

    static LoginResponse from_json(const json& j) {
        return {
            j.at("result").get<int32_t>(),
            j.value("error_msg", "")
        };
    }
};


// 群聊消息 (GROUP_MSG_SEND)
struct GroupMessageSend {
    std::string sender_id;
    std::string content;

    static json to_json(const GroupMessageSend& msg) {
        return {
            {"sender_id", msg.sender_id},
            {"content", msg.content}
        };
    }

    static GroupMessageSend from_json(const json& j) {
        return {
            j.at("sender_id").get<std::string>(),
            j.at("content").get<std::string>()
        };
    }
};

// 群聊投递回执 (GROUP_MSG_ACK)
struct GroupMessageAck {
    uint32_t msg_seq;
    uint16_t success_count;
    uint16_t fail_count;
    std::vector<uint32_t> failed_members;

    static json to_json(const GroupMessageAck& ack) {
        return {
            {"msg_seq", ack.msg_seq},
            {"success_count", ack.success_count},
            {"fail_count", ack.fail_count},
            {"failed_members", ack.failed_members}
        };
    }

    static GroupMessageAck from_json(const json& j) {
        return {
            j.at("msg_seq").get<uint32_t>(),
            j.at("success_count").get<uint16_t>(),
            j.at("fail_count").get<uint16_t>(),
            j.at("failed_members").get<std::vector<uint32_t>>()
        };
    }
};

// 心跳消息 (HEARTBEAT)
struct Heartbeat {
    uint64_t timestamp;

    static json to_json(const Heartbeat& hb) {
        return {{"timestamp", hb.timestamp}};
    }

    static Heartbeat from_json(const json& j) {
        return {j.at("timestamp").get<uint64_t>()};
    }
};

// ACK消息体结构
struct AckMessage {
    uint32_t original_seq;  // 原始消息序号
    uint32_t ack_timestamp; // 确认时间戳
    uint16_t status;        // 0-成功，其他为错误码
    std::vector<uint32_t> failed_targets; // 失败目标列表（群聊场景）

    static json to_json(const AckMessage& ack) {
        return {
            {"original_seq", ack.original_seq},
            {"ack_timestamp", ack.ack_timestamp},
            {"status", ack.status},
            {"failed_targets", ack.failed_targets}
        };
    }

    static AckMessage from_json(const json& j) {
        return {
            j.at("original_seq").get<uint32_t>(),
            j.at("ack_timestamp").get<uint32_t>(),
            j.at("status").get<uint16_t>(),
            j.at("failed_targets").get<std::vector<uint32_t>>()
        };
    }
};

#pragma pack(pop)
// 辅助函数声明
uint32_t compute_checksum(const MessageHeader &header, const uint8_t *body, size_t body_len);
uint64_t get_timestamp(); // 获取毫秒级时间戳

#endif // MESSAGE_H
